package com.longxi.tianjintianbao.ui.presenter.quality;

import android.content.Intent;
import android.view.View;

import com.longxi.tianjintianbao.AppConst;
import com.longxi.tianjintianbao.MyApplication;
import com.longxi.tianjintianbao.R;
import com.longxi.tianjintianbao.api.ApiRetrofit;
import com.longxi.tianjintianbao.api.response.BaseResponse;
import com.longxi.tianjintianbao.api.response.HttpResult;
import com.longxi.tianjintianbao.exception.ExceptionHandle;
import com.longxi.tianjintianbao.exception.MySubscriber;
import com.longxi.tianjintianbao.listener.SelectQualityClassListListener;
import com.longxi.tianjintianbao.model.Personnel;
import com.longxi.tianjintianbao.model.quality.QualityClass;
import com.longxi.tianjintianbao.ui.activity.quality.QualityItemActivity;
import com.longxi.tianjintianbao.ui.adapter.multitype.QualityClassListViewBinder;
import com.longxi.tianjintianbao.ui.base.BaseActivity;
import com.longxi.tianjintianbao.ui.base.BasePresenter;
import com.longxi.tianjintianbao.ui.dialog_fragment.QualityStateDialogFragment;
import com.longxi.tianjintianbao.ui.view.quality.IQualityClassListAtView;
import com.longxi.tianjintianbao.utils.MyUtils;
import com.longxi.tianjintianbao.utils.NListRefresh;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import me.drakeet.multitype.Items;
import me.drakeet.multitype.MultiTypeAdapter;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class QualityClassListAtPresenter extends BasePresenter<IQualityClassListAtView> {

    private MultiTypeAdapter adapter;
    private Items items;

    private String billid = "";//单据id
    private String buildname = "";//单据id
    public List<Personnel> personnels = new ArrayList<>();//存放员工的数据 用于多选

    public String states = "";
    public List<Integer> rectifications = new ArrayList<>();

    public QualityClassListAtPresenter(BaseActivity context) {
        super(context);
    }

    public void initAdapter(){
        if(adapter == null){
            adapter = new MultiTypeAdapter();
            SelectQualityClassListListener listener = new SelectQualityClassListListener() {
                @Override
                public void onSuccess(String classid, String classname) {
                    Intent mainIntent = new Intent(mContext, QualityItemActivity.class);
                    mainIntent.putExtra(AppConst.CLASSNAME,classname);
                    mainIntent.putExtra(AppConst.CLASSID,classid);
                    mainIntent.putExtra(AppConst.BILLID,billid);
                    mContext.startActivity(mainIntent);
                }
            };
            /* 注册类型和 View 的对应关系 */
            adapter.register(QualityClass.class, new QualityClassListViewBinder(listener));
            getView().getRvContent().setAdapter(adapter);
        }
    }

    public void setBar() {
        Intent intent = mContext.getIntent();
        billid =intent.getStringExtra(AppConst.BILLID);
        buildname =intent.getStringExtra(AppConst.BUILDNAME);
        mContext.setTitle(buildname);
        mContext.setTvLeft(MyUtils.getString(R.string.back));
    }

    public void getQualityClass(){
        JSONObject object = new JSONObject();
        try {
            object.put("userid", MyApplication.loginUser.userid);
            object.put("billid", billid);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        ApiRetrofit.getInstance().getQualityClass(object)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new MySubscriber<HttpResult<QualityClass>>(mContext) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable throwable) {
                mContext.hideWaitingDialog();
                MyUtils.showToast(throwable.message);
            }

            @Override
            public void onNext(HttpResult<QualityClass> result) {
                states = result.getData().get(0).getState();
                rectifications.clear();
                for (QualityClass qualityClass : result.getData()) {
                    rectifications.add(Integer.valueOf(qualityClass.getRectification()));
                }

                showBtn();

                items = NListRefresh.getInstance().fjData(result,
                        getView().getRefreshLayout(),
                        items,
                        adapter,
                        mContext);
            }
        });
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == AppConst.IntentRequstCode.ACTIVITY_PERSONNEL) {
            if(data != null){
                personnels = (List<Personnel>) data.getSerializableExtra(AppConst.PERSONNEL_LISTINTENT);
                qualityStateDialogFragment.getTvPerson().setText(personnels.get(0).getUsername());
            }
        }
    }

    QualityStateDialogFragment qualityStateDialogFragment;
    public void showQualityStateDialogFragment() {
        qualityStateDialogFragment = new QualityStateDialogFragment();
        qualityStateDialogFragment.show(mContext.getFragmentManager(), "QualityStateDialogFragment");
    }

    public List<Personnel> getPersonnels(){
        if(personnels.size() == 0){
            Personnel personnel = new Personnel();
            personnel.setUserid("");
            personnel.setUsername("");
            personnels.add(personnel);
        }
        return personnels;
    }

    /**
     * 删除数据
     * @return
     */
    public boolean deletePersonnels(Personnel personnel) {
        for (int i = 0; i < personnels.size(); i++)  {
            if (personnel.getUserid().equals(personnels.get(i).getUserid())) {
                personnels.remove(i);
                return true;
            }
        }
        return false;
    }

    /**
     * 品质检查开始（结束）
     * @param button 按钮0-开始 1-结束2-生成整改
     * @param lastdate 整改需传入整改完成时间
     */
    public void saveQualityState(String button, String person, String personid, String lastdate){

        mContext.showWaitingDialog(MyUtils.getString(R.string.upload));
        JSONObject object = new JSONObject();
        try {
            object.put("userid", MyApplication.loginUser.userid);
            object.put("billid", billid);
            object.put("person", person);
            object.put("personid", personid);
            object.put("lastdate", lastdate);
            object.put("button", button);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        ApiRetrofit.getInstance().saveQualityState(object)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new MySubscriber<BaseResponse>(mContext) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable throwable) {
                mContext.hideWaitingDialog();
                MyUtils.showToast(throwable.message);
            }

            @Override
            public void onNext(BaseResponse baseResponse) {
                mContext.hideWaitingDialog();
                MyUtils.showToast(baseResponse.getMsg());
                if(isFinsh == 1){
                    getQualityClass();
                }
                if(isFinsh == 2){
                    qualityStateDialogFragment.dismiss();
                }
            }
        });
    }

    //这一块瞎写的 回传数据实在没法判断都在一起了
    int isFinsh = 0;//判断按钮是结束还是整改 0无功能 1结束 2整改
    /**
     * 显示按钮
     */
    public void showBtn(){
        switch (states) {
            case "1":
                isFinsh = 1;
                getView().getBtnLogin().setText("结束");
                getView().getBtnLogin().setVisibility(View.VISIBLE);
                break;
            case "2":
                isFinsh = 2;
                int index = rectifications.indexOf(1);
                if(index != -1){
                    getView().getBtnLogin().setText("生成整改");
                    getView().getBtnLogin().setVisibility(View.VISIBLE);
                }
                break;
            default:
                getView().getBtnLogin().setVisibility(View.GONE);
                break;
        }
    }

    public void goFinshOrChange() {
        switch (states) {
            case "1":
                saveQualityState("1", "", "", "");
                break;
            case "2":
                int index = rectifications.indexOf(1);
                if(index != -1){
                    showQualityStateDialogFragment();
                }
                break;
        }
    }
    //这一块瞎写的 回传数据实在没法判断都在一起了
}
